package com.newhero.app.report.web.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.newhero.product.common.controller.BaseController;
import com.newhero.product.common.csrf.CsrfToken;
import com.newhero.product.common.mybatis.plugins.Page;
import com.newhero.product.common.util.CaptchaUtils;
import com.newhero.product.common.util.StringUtils;
import com.newhero.product.common.vo.Json;
import com.newhero.product.module.sys.model.User;
import com.newhero.product.module.sys.service.IAppService;
import com.newhero.product.module.sys.service.IConfigService;
import com.newhero.product.module.sys.service.IUserService;

@Controller
public class BisIndexController extends BaseController {

	@Autowired
	private IAppService appServiceImpl;
	@Autowired
	private IUserService userServiceImpl;
	
	
	@GetMapping("/login")
	public String login(HttpServletRequest request) {
		
		logger.info("GET请求登录");
		//判断是否已登录
		if (SecurityUtils.getSubject().isAuthenticated()) {
			return "redirect:/index";
		}
		// 1-需要验证码 0-不用验证码
		String needVC = configServiceImpl.getConfigItemValue(_ITEM_ADMIN_VERIFICATIONCODE);
		request.setAttribute("needVC", needVC);
		return "report/login";
	}
	
	@PostMapping("/login")
	@ResponseBody
	public Object loginPost(
			HttpServletRequest request,
			String userLoginName,
			String userPwd,
			String captcha,
			@RequestParam(value = "rememberMe", defaultValue = "1") Integer rememberMe) {
		logger.info("POST请求登录");
		
		// 1-需要验证码 0-不用验证码
		String needVC = configServiceImpl
				.getConfigItemValue(_ITEM_ADMIN_VERIFICATIONCODE);
		// 改为全部抛出异常，避免ajax csrf token被刷新
		if (StringUtils.isBlank(userLoginName)) {
			throw new RuntimeException("用户名不能为空");
		}
		if (StringUtils.isBlank(userPwd)) {
			throw new RuntimeException("密码不能为空");
		}
		if (needVC != null && "1".equals(needVC.trim())) {
			if (StringUtils.isBlank(captcha)) {
				throw new RuntimeException("验证码不能为空");
			}
			if (!CaptchaUtils.validate(request, captcha)) {
				throw new RuntimeException("验证码错误");
			}
		}

		Subject user = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(userLoginName,
				userPwd);
		// 设置记住密码
		// token.setRememberMe(1 == rememberMe);
		try {
			user.login(token);
			return renderSuccess();
		} catch (UnknownAccountException e) {
			throw new RuntimeException("账号不存在！", e);
		} catch (DisabledAccountException e) {
			throw new RuntimeException("账号未启用！", e);
		} catch (IncorrectCredentialsException e) {
			throw new RuntimeException("密码错误！", e);
		} catch (Throwable e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
	@GetMapping("/myPwd")
	public String myPwd(HttpServletRequest request) {
		request.setAttribute("userID", getUserID());
		return "report/myPwd";
	}
	
	@GetMapping("/menu")
	public String menu(HttpServletRequest request,Model model) {
		String userID = super.getUserID();
		List<Map<String, Object>> topMenuList = appServiceImpl
				.getTopMenuListWithAuth(userID);
		model.addAttribute("topMenuList", topMenuList);

		List<Map<String, Object>> secondLevelMenuList = appServiceImpl
				.getNextLevelMenuListWithAuth(userID, 2, topMenuList);
		model.addAttribute("secondLevelMenuList", secondLevelMenuList);
		return "report/menu";
	}
	
	@Autowired
	private IConfigService configServiceImpl;
	
	@GetMapping("/index")
	public String index(Model model) {

		String userID = super.getUserID();

		List<Map<String, Object>> topMenuList = appServiceImpl
				.getTopMenuListWithAuth(userID);
		model.addAttribute("topMenuList", topMenuList);

		List<Map<String, Object>> secondLevelMenuList = appServiceImpl
				.getNextLevelMenuListWithAuth(userID, topMenuList);
		
		model.addAttribute("secondLevelMenuList", secondLevelMenuList);
		model.addAttribute("userName", super.getUserName());

		return "report/index";
	}
	
	@GetMapping("/logOut")
	public Object logout() {
		logger.info("登出");
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "redirect:login";
	}
	
	@RequestMapping(value = "/myInfo", method = RequestMethod.GET)
	public String myInfo(HttpServletRequest request,
			HttpServletResponse response) {
		User user = userServiceImpl.selectById(getUserID());
		request.setAttribute("user", user);
		return "report/myInfo";
	}

	@RequestMapping(value = "/needToDoList", method = RequestMethod.POST)
	public String needToDoList(
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model){
		
		return "report/sendfile/welcomOfNeedToDoList";
	}
}
